<?php

    /**
     * Prints, preview and send voucher/invoice
     */
    class voucher_invoice_lib {

        public function voucherData($reservation_ID, $agency, $translate) {

            $CI = & get_instance();

            $data['web_site'] = $agency['web_site'];
            $data['access_url'] = $agency['access_url'];
            $data['address_agency'] = $agency['address'];
            $data['name_agency'] = $agency['name'];
            $data['agency'] = $agency;

            $CI->load->model('reservations_model');
            $CI->load->model('objects_model');
            $CI->load->model('rooms_model');
            $CI->load->helper('fields');
            $CI->load->helper('percent');


            $reservation = $CI->reservations_model->find_by_id($reservation_ID);
            $passengers = $CI->reservations_model->find_passengers($reservation_ID);


            $top_passenger = $passengers[0];

            $data['title'] = 'TOURIST VOUCHER #' . $reservation['ID'];
            $data['title_notice'] = 'NAJAVA REZERVACIJE #' . $reservation['ID'];
            $data['reservation_ID'] = $reservation['ID'];
            $data['cancellation_link'] = 'http://www.' . $agency['web_site'] . '/en/hotels/reservation_cancellation?reservation_ID=' . $reservation['ID'];
            $data['arrival'] = date('d.m.Y', $reservation['start']);
            $data['departure'] = date('d.m.Y', $reservation['end']);
            $data['client'] = $top_passenger['name'] . ' ' . $top_passenger['surname'];
            $data['email'] = $top_passenger['email'];
            $data['mobile_phone'] = $top_passenger['mobile_phone'];
            $data['address'] = $top_passenger['address'];
            $data['city'] = $top_passenger['birth_place'];
            $data['zip'] = $top_passenger['zip_code'];
            $data['country'] = $top_passenger['country'];
            $data['persons'] = $reservation['nr_persons'];
            $data['adults'] = $reservation['nr_adults'];
            $data['childrens'] = $reservation['nr_childrens'];
            $data['payment_method'] = $reservation['payment_method'];
            $data['payment_options'] = $reservation['payment_options'];
            $data['status'] = $reservation['status'];
            $data['active_lang'] = $reservation['active_lang'];

            // Load language file from reservation created language
            if (!isset($data['active_lang']) || $data['active_lang'] == "")
                $data['active_lang'] = "en";

            // get rooms, get object based on room_ID, parse object array, get serialized fields, translate object
            $room = $translate->asoc_array($CI->rooms_model->find_by_id($reservation['rooms_ID']), $data['active_lang']);

            $object3 = $CI->objects_model->list_by_id($room['objects_ID']);
            $object2 = fileds_row_array($object3, "object_fields");
            $object = $translate->asoc_array($object2, $data['active_lang']);


            $room_description = $room['description'];
            if ($room_description != "")
                $room_description = ' - ' . $room_description;

            $data['room_type_service'] = $room['name'] . $room_description . ', ' . $room['service_name'];

            $data['destination'] = $object['destination_name'];
            $data['accommodation'] = $object['object_name'] . ', ' . $room['name'] . $room_description . ', ' . $data['destination'];
            $data['accommodation_only'] = $object['object_name'];
            $data['contact_email'] = $object['object_contact_email'];
            $data['partner_name'] = $object['partner_name'];
            $data['room_type'] = $room['name'];
            $data['room_description'] = $room['description'];
            $data['service'] = $room['service_name'];

            // Backward compatible
            $data['service_total'] = isset($reservation['selling_total']) ? $reservation['selling_total'] : $reservation['price_total'];
            $data['total'] = $reservation['price_total'];

            // Advanced Payment
            if ($data['payment_options'] === '30% now and 70% balance upon arrival' || $data['payment_options'] === '30% now and 70% balance 10 days before arrival'):
                $data['advance_payment'] = find_percent(30, $reservation['price_total']);
//                $data['rest_of_payment_total'] = $data['total'] - $data['advance_payment'];
            endif;

            // Load tax
            loadClass('tax_calculation', TRUE);
            $CI->load->model('tax_model');
            $CI->load->helper('tax');

            // Find taxes
            $tax_row = $CI->tax_model->find_by_object($object['object_ID']);
            $data['tax'] = $tax_row;
            $tax['total'] = 0;

            if (count($tax_row) > 0 && $tax_row['included']):

                $nr_nights = calculateDays($reservation['start'], $reservation['end']);
                $tax = find_tax($tax_row, $nr_nights, $reservation['nr_adults'], unserialize($reservation['child_ages']));
                $data['tax']['total'] = $tax;

            endif;


            $cards = "";
            if (isset($object['object_visa']) && $object['object_visa'] == '1')
                $cards = "VISA";

            if (isset($object['object_master_card']) && $object['object_master_card'] == '1') {
                if ($cards != "") {
                    $cards.=', ';
                }
                $cards .= "Master Card";
            }


            if (isset($object['object_diners_club']) && $object['object_diners_club'] == '1') {
                if ($cards != "") {
                    $cards.=', ';
                }
                $cards .= "Diners Club";
            }


            if (isset($object['object_maestro']) && $object['object_maestro'] == '1') {
                if ($cards != "") {
                    $cards.=', ';
                }
                $cards .= "Maestro";
            }

            $data['cards'] = $cards;

            return $data;
        }

        public function printPDF($data) {

            // Load Class
            require_once('./plugins/pdf/tcpdf/config/tcpdf_config.php');
            require_once('./plugins/pdf/tcpdf/MYPDF.php');

            // create a PDF object
            $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

            // set Header and Footer
            $data['agency']['office_hours'] = lang('customer_suport_department_text') . ' ' . $data['agency']['infoline'] . ', www.' . $data['agency']['web_site'];
            $pdf->setAgency($data['agency']);

            // set document (meta) information
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('iBookHotel');
            $pdf->SetTitle($data['title']);
            $pdf->SetSubject('Tourist Voucher');
            $pdf->SetKeywords('PDF');

            // add a page
            $pdf->AddPage();

            //Create TextBox: ($textval, $x = 0, $y, $width = 0, $height = 10, $fontsize = 10, $fontstyle = '', $align = 'L')
            // create address box 
            $addressX = 180;     // address x position
            $addressY = 3;       // address y position
            $addressPB = 4;      // addres padding bootm
            $addressFS = 9;      // address font size
            // Current Y Position
            $curY = $addressY + $addressPB;

            // Padding TOP
            $PT = 13;
            $PTS = 7;
            $PTSM = 4;

            // Font size
            $FS = 9;
            $TFS = 12;

            foreach ($data['agency']['address_invoice'] as $address_line) :

                $pdf->CreateTextBox($address_line, 10, $curY + 4, $addressX, $FS, $addressFS, 'N', 'R');
                $curY += $addressPB;


            endforeach;


            // Voucher title / number
            $pdf->CreateTextBox($data['title'], 0, $curY+=10, 120, 20, 16, 'B');


            // Customer Support Department
            $pdf->CreateTextBox(lang('customer_suport_department'), 0, $curY+=$PT, 120, 20, $TFS, 'B');
            $text = lang('customer_suport_department_text') . ' ' . $data['agency']['infoline'] . ', www.' . $data['agency']['web_site'];
            $pdf->CreateTextBox($text, 0, $curY+=$PTS, 120, 20, $FS);

            $offset = 50;

            // Accommodation Confirmation
            $pdf->CreateTextBox(lang('accommodation_confirmation'), 0, $curY+=$PT, 120, 20, $TFS, 'B');
            $pdf->CreateTextBox(lang('destination') . ":", 0, $curY + $PTS, 120, 20, $FS);
            $pdf->CreateTextBox($data['destination'] . ', Montenegro', $offset, $curY+=$PTS, 120, 20, $FS);
            $pdf->CreateTextBox(lang('accommodation') . ":", 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(strip_tags($data['accommodation']) . ', ' . $data['agency']['email'], $offset, $curY+=$PTSM, 120, 20, $FS);

            // Guest Arrival & Info

            $pdf->CreateTextBox(lang('client_arrival_departure') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox($data['arrival'] . ' / ' . $data['departure'], $offset, $curY+=$PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang('client_name') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox($data['client'], $offset, $curY+=$PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang('client_address') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox($data['address'], $offset, $curY+=$PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang('client_city') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox($data['city'], $offset, $curY+=$PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang('client_zip') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox($data['zip'] . ' ' . $data['country'], $offset, $curY+=$PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang('client_nr_persons') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox($data['persons'], $offset, $curY+=$PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang('client_payment_method') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox($data['payment_method'], $offset, $curY+=$PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang('client_payment_options') . ':', 0, $curY + $PTSM, 120, 20, $FS);
            $pdf->CreateTextBox(lang($data['payment_options']), $offset, $curY+=$PTSM, 120, 20, $FS);



            // Total Price
            $pdf->CreateTextBox(lang('total_price'), 0, $curY+=$PT, 120, 20, $TFS, 'B');
            $pdf->Line(10, $curY + 15, 195, $curY +=15);


            // Invocie Data
            $orders[] = array('item' => lang('room_service') . ':', 'descr' => $data['room_type_service'], 'price' => $data['service_total']);

            if (isset($data['tax']['included']) && $data['tax']['included'] == 1):
                $orders[] = array('item' => '', 'descr' => lang('city_tax'), 'price' => $data['tax']['total']['city']);
                $orders[] = array('item' => '', 'descr' => lang('insurance_tax'), 'price' => $data['tax']['total']['insurance']);

                if ($data['tax']['eco'] != 0)
                    $orders[] = array('item' => '', 'descr' => lang('eco_tax'), 'price' => $data['tax']['total']['eco']);
            endif;

            // The Advanced Payment Row
            if (isset($data['advance_payment'])) {

                switch ($data['payment_options']):

                    case '30% now and 70% balance upon arrival':
                        $total_text = lang('now_30_70_upon_arrival');
                        break;

                    case '30% now and 70% balance 10 days before arrival':
                        $total_text = lang('now_30_70_upon_10_days_before_arrival');
                        break;

                endswitch;

                $orders[] = array('item' => lang('advanced_payment') . ':', 'descr' => lang('upon_inquiry_30'), 'price' => $data['advance_payment']);
                $data['total'] -= $data['advance_payment'];
            } else
                $total_text = lang('total');




//            $curY = $curY;
//            $total = 0;
            foreach ($orders as $row) {
                $pdf->CreateTextBox($row['item'], 2, $curY, 20, 10, $FS, '', 'L');
                $pdf->CreateTextBox($row['descr'], 39, $curY, 120, 10, $FS, '');
                $pdf->CreateTextBox('€' . number_format($row['price'], 2, '.', ''), 152, $curY, 30, 10, $FS, '', 'R');
                $curY += 5;

//                $total += $row['price'];
            }
            $pdf->Line(10, $curY + 5, 195, $curY +=5);


            // The Total Row
            $pdf->CreateTextBox($total_text, 0, $curY, 155, 10, $FS, 'N', 'L');
            $pdf->CreateTextBox('€' . number_format($data['total'], 2, '.', ''), 152, $curY, 30, 10, $FS, 'B', 'R');


            // VAT
            $pdf->CreateTextBox('- ' . lang('ovreall_cost'), 0, $curY+=4, 0, 20, $FS, 'N');
            $pdf->CreateTextBox(lang('cost_by_the_client'), 2, $curY+=4, 0, 20, $FS, 'N');
            $pdf->CreateTextBox('- ' . lang('vat'), 0, $curY+=4, 0, 20, $FS, 'N');

            if (isset($data['tax']['included']) && $data['tax']['included'] == 1):

            else:
                $pdf->CreateTextBox('- ' . lang('dtl.tax_not_included'), 0, $curY+=4, 0, 20, $FS, 'N');


                if (isset($data['tax']['included'])):
                    $buildTaxStr = ' ' . lang('city_tax') . ': ' . $data['tax']['city'] . ' (' . lang('day') . '), ';
                    $buildTaxStr.= lang('insurance_tax') . ': ' . $data['tax']['insurance'] . ' (' . lang('day') . ')';
                    if ($data['tax']['eco'] != 0)
                        $buildTaxStr.= ', ' . lang('eco_tax') . ': ' . $data['tax']['eco'] . ' (' . lang('day') . ')';

                    $pdf->CreateTextBox(' ' . $buildTaxStr, 0, $curY+=4, 0, 20, $FS, 'N');

                endif;



            endif;

            $pdf->CreateTextBox('- ' . lang('additional_cost'), 0, $curY+=4, 0, 20, $FS, 'N');

            //  Accepted credit cards
//            $pdf->CreateTextBox(lang('accepted_cards'), 0, $curY+=$PT, 120, 20, $TFS, 'B');
//            $pdf->CreateTextBox($data['cards'], 0, $curY+=$PTS, 120, 20, $FS);
            // Dear Guest
            $pdf->CreateTextBox(lang('dear') . ' ' . ucwords($data['client'] . ','), 0, $curY+=$PT - 3, 120, 20, $FS, 'N');

            $text = lang('thank_you_booking_with') . ' <b>' . $data['web_site'] . '</b>.<br>' . strip_tags(lang('we_hope'));

            $pdf->MultiCell(195, 0, $text, 0, 'L', 0, 1, 10, $curY + 16, true, null, true);

            $curY +=15;


            //  Explanation on how to use the voucher
            $pdf->CreateTextBox(strip_tags(lang('explanation_voucher')), 0, $curY+=$PT - 5, 120, 20, 10, 'B');
            $text = lang('provided_by') . $data['web_site'] . '. ' . lang('present_passport');
            $pdf->CreateTextBox($text, 0, $curY+=$PTS - 1, 120, 20, $FS);

            //  Accommodation Cancellation
            $pdf->CreateTextBox(lang('cancelation'), 0, $curY+=$PT, 120, 20, $TFS, 'B');
            $text = lang('use_folowing_link') . ":";
            $pdf->CreateTextBox($text, 0, $curY+=$PTS, 120, 20, $FS);

            $text = '<a href="' . $data['cancellation_link'] . '">' . $data['cancellation_link'] . '</a>';

            $pdf->MultiCell(175, 0, $text, 0, 'L', 0, 1, 10, $curY + 13, true, null, true);




            //Close and output PDF document
            $pdf->SetFont(PDF_FONT_NAME_MAIN, '', $FS);

            return $pdf;
        }

    }
    